#include <iostream>

#include <nsServiceManagerUtils.h>
#include <mozStorageCID.h>
#include <nsAppDirectoryServiceDefs.h>
#include <nsDirectoryServiceUtils.h>
#include <nsStringAPI.h>

#include "MapLrcFile.h"
#include "PlayerManager.h"

using namespace std;

CMapLrcFile::CMapLrcFile(void)
{
    cout << "CMapLrcFile::CMapLrcFile()" << endl;
    nsCOMPtr<nsIFile> dbFile;
    NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(dbFile));

    dbFile->Append(NS_LITERAL_STRING("LrcFileMap.sqlite"));

    m_dbService = do_GetService(MOZ_STORAGE_SERVICE_CONTRACTID);
    m_dbService->OpenDatabase(dbFile, getter_AddRefs(m_dbConn));

    m_dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("CREATE TABLE IF NOT EXISTS LrcFileMap(songName CHAR PRIMARY KEY NOT NULL, lrcFile CHAR NOT NULL)"));


    m_dbConn->CreateStatement(NS_LITERAL_CSTRING("SELECT lrcFile FROM LrcFileMap WHERE songName = ?1"), getter_AddRefs(m_queryStatement));
    m_dbConn->CreateStatement(NS_LITERAL_CSTRING("INSERT INTO LrcFileMap VALUES (?1, ?2)"), getter_AddRefs(m_insertStatement));
    m_dbConn->CreateStatement(NS_LITERAL_CSTRING("UPDATE LrcFileMap SET lrcFile = ?1 WHERE songName = ?2"), getter_AddRefs(m_updateStatement));

}

CMapLrcFile::~CMapLrcFile(void)
{
    m_dbConn->Close();
}


void CMapLrcFile::SetLrcFile(const std::string &file)
{
    cout << "CMapLrcFile::SetLrcFile enter!" << endl;
    std::string songName = CPlayerManager::GetIns().GetMediaTitle();
    if( songName.empty() )
    {
        return;
    }

    m_queryStatement->BindUTF8StringParameter(0, nsCString(songName.c_str()));
    PRBool hasMoreData;
    if( NS_SUCCEEDED(m_queryStatement->ExecuteStep(&hasMoreData)) && hasMoreData )
    {
        
        while ( NS_SUCCEEDED(m_queryStatement->ExecuteStep(&hasMoreData)) && hasMoreData )
        {
            // do nothing
        }

        // update it
        m_updateStatement->BindUTF8StringParameter(0, nsCString(file.c_str()));
        m_updateStatement->BindUTF8StringParameter(1, nsCString(songName.c_str()));
        m_updateStatement->Execute();
    }
    else
    {
        // insert it
        m_insertStatement->BindUTF8StringParameter(0, nsCString(songName.c_str()));
        m_insertStatement->BindUTF8StringParameter(1, nsCString(file.c_str()));
        m_insertStatement->Execute();
    }
}

std::string CMapLrcFile::GetLrcFile(const std::string &name)
{
    cout << "CMapLrcFile::GetLrcFile enter! name = " << name << endl;
    m_queryStatement->BindUTF8StringParameter(0, nsCString(name.c_str()));
    PRBool hasMoreData;
    if( NS_SUCCEEDED(m_queryStatement->ExecuteStep(&hasMoreData)) && hasMoreData )
    {
        nsCString fileName;
        m_queryStatement->GetUTF8String(0, fileName);

        cout << "fileName = " << fileName.get() << endl;

        while ( NS_SUCCEEDED(m_queryStatement->ExecuteStep(&hasMoreData)) && hasMoreData )
        {
            // do nothing
        }

        return fileName.get();
    }

    return "";
}

